<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerSelectArticleModal"
    @cancel="onCancelSelectArticleModal"
    :title="displayModuleTitle"
    :default-fullscreen="false"
    :show-ok-btn="false"
    width="1000px"
    :body-style="{ height: '500px' }"
  >
    <BasicForm @register="registerQueryArticleConditionForm" @submit="onQueryArticleButtonClick" />
    <BasicTable
      @register="registerArticleTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="articles"
    >
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ep:select',
              label: '选择',
              onClick: onChooseArticle.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, computed } from 'vue';
  import moment from 'moment';

  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';

  import { queryArticles } from '/@/api/cms/display';
  import { ArticleQueryConditionDto } from '/@/api/cms/model/articleModel';

  /**
   * 定义查询文件的条件表单
   */
  const articlesQueryConditionFormSchema: FormSchema[] = [
    // 素材来源为从已发布文章中选择时需要设置查询文章的条件：栏目ID、查询时间段
    {
      field: 'queryArticleCategoryFlag',
      label: '查询文章栏目',
      component: 'Select',
      required: true,
      colProps: { span: 8 },
      componentProps: {
        options: [
          { label: '只在当前栏目中', value: 0 },
          { label: '查询所有栏目', value: 1 },
        ],
        allowClear: false,
      },
      defaultValue: 0,
    },
    {
      field: 'queryArticleTimeType',
      label: '文章发布时间段',
      component: 'Select',
      required: true,
      colProps: { span: 8 },
      componentProps: {
        options: [
          { label: '今天内', value: 1 },
          { label: '3天内', value: 3 },
          { label: '7天内', value: 7 },
          { label: '15天内', value: 15 },
          { label: '30天内', value: 30 },
        ],
        allowClear: false,
      },
      defaultValue: 7,
    },
  ];

  /**
   * 定义文章表格的表头
   */
  export const articlesTableColumns: BasicColumn[] = [
    {
      title: 'ID', //显示表头名称
      dataIndex: 'id', //显示数据的字段名或序号
      //   fixed: 'left', //表格列固定，取值：'left'|'right'|boolean
      ifShow: true, //设置在表格界面中是否显示
      width: 50,
    },
    {
      title: '栏目',
      dataIndex: 'cid',
      //   fixed: 'left', //表格列固定在左边
      ifShow: false,
      width: 120,
    },
    {
      title: '标题',
      dataIndex: 'title',
      //   fixed: 'left', //表格列固定在左边
      align: 'left',
      width: 120,
      slots: { customRender: 'titleRender' },
    },
    {
      title: '来源',
      dataIndex: 'source',
      ifShow: false,
      width: 120,
    },
    {
      title: '作者',
      dataIndex: 'author',
      ifShow: false,
      width: 120,
    },
    {
      title: '起草时间',
      dataIndex: 'intm',
      width: 100,
    },
    {
      title: '起草人',
      dataIndex: 'inuser',
      width: 100,
    },
    {
      title: '部门',
      dataIndex: 'indept',
      width: 100,
    },
  ];

  export default defineComponent({
    name: 'SwipperSelectFromArticle',
    components: { BasicModal, BasicTable, TableAction, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      //栏目id
      const categoryId = ref('');
      //栏目名称
      const categoryName = ref('');
      //查询文章的结果集合
      const articles = ref([]);

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const [registerQueryArticleConditionForm, { getFieldsValue, resetFields }] = useForm({
        labelWidth: 120,
        schemas: articlesQueryConditionFormSchema,
        showActionButtonGroup: true,
        showResetButton: false,
        actionColOptions: {
          span: 6,
        },
      });

      const [registerArticleTable] = useTable({
        title: '从已发布文章中选择',
        columns: articlesTableColumns,
        formActions: [], //调用查询文章方法
        formConfig: {
          labelWidth: 120, //设置查询表单中label的宽度
          schemas: articlesQueryConditionFormSchema,
          showResetButton: false, //查询条件部分中是否显示重置按钮
        },
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 60,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerSelectArticleModal, { setModalProps, closeModal }] = useModalInner(
        async (data: QcUnifyTransToChildProps) => {
          //接收父组件传递的数据
          console.log('registerSelectArticleModal data', data);
          if (data != undefined && data != null) {
            qcUnifyProps.value = unref(data);
            //从父组件中传递过来的栏目ID
            categoryId.value = data.dataId;
            categoryName.value = data.dataTitle;
          }

          setModalProps({ confirmLoading: false });

          //搜索文章
          onQueryArticleButtonClick();
        },
      );

      /**
       * 点击取消Modal事件
       */
      async function onCancelSelectArticleModal() {
        //重置查询条件表单
        resetFields();
      }

      /**
       * 表单查询按钮查询
       */
      async function onQueryArticleButtonClick() {
        const values = await getFieldsValue();
        console.log('onQueryArticleButtonClick values', values);
        let now = moment(new Date());
        let today = moment().month(now.month()).date(now.date()).endOf('day');
        //默认查询文章的时间段是当天
        let condition: ArticleQueryConditionDto = {
          page: 1,
          pageSize: 10,
          hasCover: true, //只查询有封面图片的文章
          begintm: today.format('YYYY-MM-DD'),
          endtm: today.add(1, 'd').format('YYYY-MM-DD'),
        };
        //根据界面中的选择条件进行转换，对查询接口中的参数进行赋值
        if (values != undefined && values != null) {
          if (values.queryArticleCategoryFlag === 0 || values.queryArticleCategoryFlag === '0') {
            // 只在当前栏目中
            condition.cid = categoryId.value;
          }
          if (values.queryArticleTimeType != undefined && values.queryArticleTimeType != null) {
            condition.begintm = today.add(-values.queryArticleTimeType, 'd').format('YYYY-MM-DD');
          }
        }

        queryArticles(condition)
          .then((res) => {
            console.log('onQueryArticleButtonClick queryArticles res', res);
            articles.value = res.items;
          })
          .catch((ex) => {
            console.log('onQueryArticleButtonClick queryArticles ex', ex);
          });
      }

      /**
       * 选择指定文章按钮点击事件
       */
      function onChooseArticle(record: Recordable) {
        console.log('onChooseArticle', record);

        //重置查询条件表单
        resetFields();

        //调用父组件事件并进行传值
        emit('success', record);
        closeModal();
      }

      return {
        displayModuleTitle,
        articles,
        registerSelectArticleModal,
        registerArticleTable,
        registerQueryArticleConditionForm,
        onCancelSelectArticleModal,
        onQueryArticleButtonClick,
        onChooseArticle,
      };
    },
  });
</script>
